package server;


import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collections;
import java.util.LinkedList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

import classes.LocationChangeDetalis;
import classes.User;

import db.DB;
import db.DBmanager;

/**
 * jafo: 35.2213279 31.7808326
 * shlomzi 35.2207105 31.7802707
 * coresh 35.2228791 31.7795602
 * 
 */
/**
 * Servlet implementation class ChangeLocation
 */
public class ChangeLocation extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ChangeLocation() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * 
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try{
	//**** getting user details***************************************************************************
			String lat=request.getParameterValues("lat")[0];
			String lng=request.getParameterValues("lng")[0];
			String userName=request.getParameterValues("userName")[0];
			String url = "http://ws.geonames.org/findNearbyStreetsOSM?lat="+lat+"&lng="+lng;
			//HttpSession sess= request.getSession();
			//String userName=(String)sess.getAttribute("userName");
			User user=DBmanager.getDB().getUserByUserName(userName);

	//**** getting user curr location+checking if the new location resulted in a new action(street open for sale, street have owner...)
			String userArea=StreetsNameHelper.getTextDateByUrl(url);
			String startTag = "<name>";
			String endTag = "</name>";
			int start = userArea.indexOf(startTag)+startTag.length();
			int end = userArea.indexOf(endTag);
			
			String startTagC = "<distance>";
			String endTagC = "</distance>";
			int startC = userArea.indexOf(startTagC)+startTagC.length();
			int endC = userArea.indexOf(endTagC);
			
			//int startC=userArea.indexOf(startTagC)+startTagC.length();
			//int endC = userArea.indexOf(endTagC);
			String changeLocationResult="";
			String userLocation="";
			if(start>0 && end>0 && startC>0 && endC>0){
				double userDis=Double.parseDouble(userArea.substring(startC,endC));
				if (userDis>0.01){
					response.setStatus(200);
					return;
				}
				userLocation = userArea.substring(start, end);
				//String coordinates= userArea.substring(startC,endC);
				//DBmanager.getDB().insertStreet(userLocation,user.getUniqueKey(),"7000","3344","close",coordinates);
				//DBmanager.getDB().insertOwnedStreet(user.getUserName(), userLocation, user.getUniqueKey());
				DBmanager.getDB().printDB();
				String res=DBmanager.getDB().handleChangeLocation(userLocation,userName,user.getUniqueKey());
				if (res.equals("OK")){
					response.setStatus(200);
				}
			}


//	//*** getting the closest street distance for notifying the client when to send his new location*******
//			String surroundingStreets="";
//			surroundingStreets=userArea.substring(userArea.indexOf("</streetSegment>")+10);
//			LinkedList<Double> distances=new LinkedList<Double>();
//			String dis="<distance>";
//			while(surroundingStreets.indexOf("<distance>")!=-1){
//				int beginI=surroundingStreets.indexOf("<distance>");
//				int endI=surroundingStreets.indexOf("</distance>");
//				distances.add(Double.parseDouble(surroundingStreets.substring(beginI+dis.length(),endI)));
//				surroundingStreets=surroundingStreets.substring(endI+dis.length()+1);  
//			}
//			Double closestStreet=Collections.min(distances);
//			System.out.println(distances);
//			System.out.println(userLocation);
//			System.out.println("closestStreet:  "+ closestStreet);
//
//	//*** converting all the gathered info to a Json obj*******************************************
//			PrintWriter out=response.getWriter();
//			Gson gson=new Gson();
//			LocationChangeDetalis locatingChangeDet=new LocationChangeDetalis();
//			locatingChangeDet.set_closestStreetDis(closestStreet+"");
//			locatingChangeDet.set_newLocationMsg(changeLocationResult);
			
//			out.write(gson.toJson(locatingChangeDet));
//			System.out.println("********************");
//			System.out.println(gson.toJson(locatingChangeDet));
		}catch(Exception e){
			e.printStackTrace();
			PrintWriter out=response.getWriter();
			out.write("we have encountered a technical problem while retriving your location");
			response.setStatus(400);
			
		}



	}



	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
